﻿using log4net;
using MediatR;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using xiaodingmarket_Domain_core.Bus;
using xiaodingmarket_Domain_core.Commands;
using xiaodingmarket_Domain_core.Events;

namespace Infra_Bus
{
    /// <summary>
    /// 一个密封类，实现我们的中介记忆总线
    /// </summary>
    public sealed class InMemoryBus : IMediatorHandler
    {
        //构造函数注入
        private readonly IMediator _mediator;
        private readonly IEventStoreService _eventStore;

        public InMemoryBus(IEventStoreService eventStore, IMediator mediator)
        {
            _eventStore = eventStore;
            _mediator = mediator;

        }



        public Task RaiseEvent<T>(T @event) where T : Event
        {
            //除了领域错误事件通知其他的应该是在这里进行保存
            if (!@event.MessageType.Equals("DomainNotification"))
                _eventStore?.Save(@event);
            //// MediatR中介者模式中的第二种方法，发布/订阅模式
            ///不需要对请求进行必要的响应，与请求/响应模式作对比
            return _mediator.Publish(@event);
        }

        /// <summary>
        /// 实现我们在IMediatorHandler中定义的接口
        /// 没有返回值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="command"></param>
        /// <returns></returns>
        public Task SendCommand<T>(T command) where T : Command
        {
            return _mediator.Send(command);//这里要注意下 command 对象
        }

    }
}
